<template>
  <div class="event-query-panel">
    <!-- 查询条件 -->
    <a-card title="查询条件" :bordered="false" style="margin-bottom: 16px">
      <a-form layout="inline" :model="queryForm">
        <a-form-item label="事件名称">
          <a-input
            v-model:value="queryForm.name"
            placeholder="请输入事件名称"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="事件类型">
          <a-select
            v-model:value="queryForm.type"
            placeholder="请选择事件类型"
            style="width: 150px"
            allow-clear
          >
            <a-select-option
              v-for="type in eventTypes"
              :key="type.value"
              :value="type.value"
            >
              {{ type.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="优先级">
          <a-select
            v-model:value="queryForm.priority"
            placeholder="请选择优先级"
            style="width: 120px"
            allow-clear
          >
            <a-select-option
              v-for="priority in priorities"
              :key="priority.value"
              :value="priority.value"
            >
              {{ priority.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="时间范围">
          <a-range-picker
            v-model:value="queryForm.dateRange"
            style="width: 240px"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleQuery">
              <template #icon>
                <IconifyIcon icon="ant-design:search-outlined" />
              </template>
              查询
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <IconifyIcon icon="ant-design:reload-outlined" />
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 查询结果 -->
    <a-card title="查询结果" :bordered="false">
      <template #extra>
        <a-space>
          <a-button @click="refreshData">
            <template #icon>
              <IconifyIcon icon="ant-design:reload-outlined" />
            </template>
            刷新
          </a-button>
          <a-button @click="exportData">
            <template #icon>
              <IconifyIcon icon="ant-design:download-outlined" />
            </template>
            导出
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="queryResults"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getEventTypeColor(record.type)">
              {{ getEventTypeLabel(record.type) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'priority'">
            <a-tag :color="getPriorityColor(record.priority)">
              {{ getPriorityLabel(record.priority) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="showDetailModal(record)"
              >
                详情
              </a-button>
              <a-button type="link" size="small" @click="handleReplay(record)">
                重放
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 事件详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="事件详情"
      width="900px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="事件ID">
          {{ selectedEvent?.id }}
        </a-descriptions-item>
        <a-descriptions-item label="事件名称">
          {{ selectedEvent?.name }}
        </a-descriptions-item>
        <a-descriptions-item label="事件类型">
          <a-tag :color="getEventTypeColor(selectedEvent?.type)">
            {{ getEventTypeLabel(selectedEvent?.type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="优先级">
          <a-tag :color="getPriorityColor(selectedEvent?.priority)">
            {{ getPriorityLabel(selectedEvent?.priority) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(selectedEvent?.status)">
            {{ getStatusLabel(selectedEvent?.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="触发时间">
          {{ selectedEvent?.triggerTime }}
        </a-descriptions-item>
        <a-descriptions-item label="处理时间" :span="2">
          {{ selectedEvent?.processTime }}
        </a-descriptions-item>
        <a-descriptions-item label="事件描述" :span="2">
          {{ selectedEvent?.description }}
        </a-descriptions-item>
        <a-descriptions-item label="事件数据" :span="2">
          <pre>{{ selectedEvent?.eventData }}</pre>
        </a-descriptions-item>
        <a-descriptions-item label="触发条件" :span="2">
          {{ selectedEvent?.triggerCondition }}
        </a-descriptions-item>
        <a-descriptions-item label="处理结果" :span="2">
          <pre>{{ selectedEvent?.processResult }}</pre>
        </a-descriptions-item>
        <a-descriptions-item
          label="错误信息"
          :span="2"
          v-if="selectedEvent?.errorMessage"
        >
          <pre style="color: red">{{ selectedEvent?.errorMessage }}</pre>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'event-selected': [event: any];
}>();

// 响应式数据
const loading = ref(false);
const detailModalVisible = ref(false);
const selectedEvent = ref<any>(null);

// 查询表单
const queryForm = reactive({
  name: '',
  type: '',
  priority: '',
  dateRange: [],
});

// 事件类型
const eventTypes = [
  { value: 'CREATE', label: '创建事件' },
  { value: 'UPDATE', label: '更新事件' },
  { value: 'DELETE', label: '删除事件' },
  { value: 'START', label: '启动事件' },
  { value: 'STOP', label: '停止事件' },
  { value: 'ERROR', label: '错误事件' },
  { value: 'WARNING', label: '警告事件' },
  { value: 'INFO', label: '信息事件' },
  { value: 'CUSTOM', label: '自定义事件' },
];

// 优先级
const priorities = [
  { value: 'LOW', label: '低' },
  { value: 'MEDIUM', label: '中' },
  { value: 'HIGH', label: '高' },
  { value: 'URGENT', label: '紧急' },
];

// 事件状态
const eventStatuses = [
  { value: 'PENDING', label: '待处理' },
  { value: 'PROCESSING', label: '处理中' },
  { value: 'SUCCESS', label: '成功' },
  { value: 'FAILED', label: '失败' },
  { value: 'CANCELLED', label: '已取消' },
];

// 模拟查询结果数据
const queryResults = ref([
  {
    id: '1',
    name: '资源创建事件',
    type: 'CREATE',
    priority: 'MEDIUM',
    status: 'SUCCESS',
    description: '当资源被创建时触发的事件',
    eventData:
      '{"resourceId": "res_001", "action": "create", "timestamp": "2024-01-15T10:30:00Z"}',
    triggerCondition: 'resource.status === "CREATED"',
    triggerTime: '2024-01-15 10:30:00',
    processTime: '2024-01-15 10:30:05',
    processResult: '{"success": true, "message": "资源创建成功"}',
  },
  {
    id: '2',
    name: '资源状态变更事件',
    type: 'UPDATE',
    priority: 'HIGH',
    status: 'SUCCESS',
    description: '当资源状态发生变更时触发的事件',
    eventData:
      '{"resourceId": "res_002", "oldStatus": "CREATED", "newStatus": "RUNNING", "timestamp": "2024-01-15T11:00:00Z"}',
    triggerCondition: 'resource.status !== resource.oldStatus',
    triggerTime: '2024-01-15 11:00:00',
    processTime: '2024-01-15 11:00:03',
    processResult: '{"success": true, "message": "状态更新成功"}',
  },
  {
    id: '3',
    name: '资源删除事件',
    type: 'DELETE',
    priority: 'HIGH',
    status: 'FAILED',
    description: '当资源被删除时触发的事件',
    eventData:
      '{"resourceId": "res_003", "action": "delete", "timestamp": "2024-01-15T11:30:00Z"}',
    triggerCondition: 'resource.status === "DELETED"',
    triggerTime: '2024-01-15 11:30:00',
    processTime: '2024-01-15 11:30:10',
    processResult: '{"success": false, "message": "删除失败"}',
    errorMessage: '资源正在使用中，无法删除',
  },
  {
    id: '4',
    name: '系统警告事件',
    type: 'WARNING',
    priority: 'MEDIUM',
    status: 'SUCCESS',
    description: '系统资源使用率过高警告',
    eventData:
      '{"resourceId": "res_004", "cpuUsage": 85, "memoryUsage": 90, "timestamp": "2024-01-15T12:00:00Z"}',
    triggerCondition: 'cpuUsage > 80 || memoryUsage > 85',
    triggerTime: '2024-01-15 12:00:00',
    processTime: '2024-01-15 12:00:02',
    processResult: '{"success": true, "message": "警告已发送"}',
  },
]);

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列配置
const columns = [
  {
    title: '事件ID',
    dataIndex: 'id',
    key: 'id',
    width: 100,
  },
  {
    title: '事件名称',
    dataIndex: 'name',
    key: 'name',
    width: 180,
  },
  {
    title: '事件类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '触发时间',
    dataIndex: 'triggerTime',
    key: 'triggerTime',
    width: 160,
  },
  {
    title: '处理时间',
    dataIndex: 'processTime',
    key: 'processTime',
    width: 160,
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right',
  },
];

// 方法
const loadData = () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    pagination.value.total = queryResults.value.length;
    loading.value = false;
  }, 500);
};

const handleQuery = () => {
  console.log('查询条件:', queryForm);
  loadData();
  message.success('查询完成');
};

const handleReset = () => {
  Object.assign(queryForm, {
    name: '',
    type: '',
    priority: '',
    dateRange: [],
  });
  loadData();
  message.success('查询条件已重置');
};

const refreshData = () => {
  loadData();
  message.success('数据刷新成功');
};

const exportData = () => {
  message.success('数据导出功能开发中...');
};

const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  loadData();
};

const showDetailModal = (record: any) => {
  selectedEvent.value = record;
  detailModalVisible.value = true;
  emit('event-selected', record);
};

const closeDetailModal = () => {
  detailModalVisible.value = false;
  selectedEvent.value = null;
};

const handleReplay = (record: any) => {
  message.success(`事件 ${record.name} 重放功能开发中...`);
};

const getEventTypeLabel = (type: string) => {
  const eventType = eventTypes.find((t) => t.value === type);
  return eventType?.label || type;
};

const getEventTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    CREATE: 'green',
    UPDATE: 'blue',
    DELETE: 'red',
    START: 'cyan',
    STOP: 'orange',
    ERROR: 'red',
    WARNING: 'orange',
    INFO: 'blue',
    CUSTOM: 'purple',
  };
  return colorMap[type] || 'default';
};

const getPriorityLabel = (priority: string) => {
  const priorityItem = priorities.find((p) => p.value === priority);
  return priorityItem?.label || priority;
};

const getPriorityColor = (priority: string) => {
  const colorMap: Record<string, string> = {
    LOW: 'default',
    MEDIUM: 'blue',
    HIGH: 'orange',
    URGENT: 'red',
  };
  return colorMap[priority] || 'default';
};

const getStatusLabel = (status: string) => {
  const statusItem = eventStatuses.find((s) => s.value === status);
  return statusItem?.label || status;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'default',
    PROCESSING: 'blue',
    SUCCESS: 'green',
    FAILED: 'red',
    CANCELLED: 'orange',
  };
  return colorMap[status] || 'default';
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.event-query-panel {
  pre {
    background: #f5f5f5;
    padding: 8px;
    border-radius: 4px;
    font-size: 12px;
    max-height: 200px;
    overflow: auto;
  }
}
</style>
